﻿using UnityEngine;
using System.Collections;
using Action = System.Action;

/// <summary>
/// Script responsible for aiming and launching the ball.
/// </summary>
public class Launcher : MonoBehaviour {
	
	/// <summary>
	/// The ball to launch. Should be a pre-instantiated object (not a prefab).
	/// </summary>
	public GameObject BallToLaunch;
	
	/// <summary>
	/// GameObject used for representing the direction at which the player is aiming.
	/// </summary>
	public GameObject LauncherArrow;
	
	/// <summary>
	/// The launch force coefficient. The ball will be set to travel at the speed set here.
	/// </summary>
	public float LaunchForceCoefficient;
	
	/// <summary>
	/// Event triggered when the ball is launched.
	/// </summary>
	public event Action OnBallLaunch;
	
	// Use this for initialization
	void Start () {
		Quaternion id = Quaternion.identity;
		print(string.Format("x = {0}, y = {1}, z = {2}, w = {3}", id.x, id.y, id.z, id.w));
	}
	
	/// <summary>
	/// Launches the ball in the specified direction.
	/// </summary>
	/// <param name='direction'>
	/// Direction in which to launch the ball.
	/// </param>
	void Launch(Vector2 direction)
	{
		// Don't bother to launch if there is no ball
		if (BallToLaunch == null)
			return;
		
		// Give the ball velocity
		BallToLaunch.GetComponent<BallBounce>().AddVelocity(direction * LaunchForceCoefficient);
		
		// Fire the launch event
		if (OnBallLaunch != null)
			OnBallLaunch();
	}
	
	// Update is called once per frame
	void Update () {
		// Find the vector going from where the launch point lies on the screen to where the mouse currently points
		Vector2 ownLocation = (Vector2)Camera.main.WorldToScreenPoint(transform.position);
		Vector2 launchVector = (Vector2)Input.mousePosition - ownLocation;
		
		LauncherArrow.transform.right = launchVector.normalized;
		
		// Check for an LMB click
		bool launchTriggered = Input.GetMouseButtonDown(0);
		
		// Launch the ball if the left mouse button was pressed
		// The ball should travel in the direction of the launch vector
		if (launchTriggered)
		{
			Launch(launchVector.normalized);
			gameObject.SetActive(false);
		}
	}
}
